<?php namespace Phpcmf\Model\Fuwu;

// 模块内容模型类

class Content extends \Phpcmf\Model\Content {


    // 内容显示
    public function _call_show($data) {

        $url = '';
        $son = $this->table(SITE_ID.'_'.MOD_DIR.'_form_son')
            ->where('cid', $data['id'])
            ->where('status=1')
            ->order_by('displayorder asc,id asc')->getAll();
        if ($son) {
            foreach ($son as $i => $t) {
                $son[$i]['url'] = dr_son_url($t);
                !$url && $url = $son[$i]['url'];
            }
        }

        $data['son_url'] = $url;
        $data['son_list'] = $this->format_son_list($son, $data['son_type']);
        $data['son_type'] = $this->format_son_type($data['son_type']);
        $data['son_type_first'] = array_key_first($data['son_type']);

        return $data;
    }

    // 阅读章节类别
    public function son_type($type) {

        $type = dr_string2array($type);
        if (!$type) {
            $type = [
                //0 => dr_lang('未命名'),
            ];
        }

        return $type;
    }

    // 前台显示阅读章节类别
    public function format_son_type($type) {

        $type = dr_string2array($type);
        if (!$type) {
            $type = [
                0 => '',
            ];
        }

        return $type;
    }

    // 加入分类
    public function add_son_type($index, $name) {

        $stype = $this->son_type($index['son_type']);
        if (!$stype) {
            $stype[1] = $name;
        } else {
            $stype[] = $name;
        }

        $this->table(dr_module_table_prefix(APP_DIR))->update($index['id'], [
            'son_type' => dr_array2string($stype)
        ]);

        return dr_return_data(1, 'ok');
    }

    // 格式化章节数据
    function format_son_list($list, $type) {

        if (!$list) {
            return [];
        }

        $type = dr_string2array($type);
        if (!$type) {
            $type = [
                0 => '',
            ];
        }

        $rt = [];
        foreach ($type as $tid => $name) {

            if (!isset($rt[$tid])) {
                $rt[$tid] = [];
            }

            if ($list) {
                foreach ($list as $i => $t) {
                    if ((int)$t['tid'] == $tid) {
                        $rt[$tid][] = $t;
                        unset($list[$i]);
                    }
                }
            }
        }


        return $rt;
    }
}